const fp = require('loadsh/fp')
const cars = [
    {
        name: 'FF',
        horsepower: 660,
        dollar_value: 700000,
        in_stock: true
    },
    {
        name: 'Spyker C12 Zagato',
        horsepower: 650,
        dollar_value: 648000,
        in_stock: false
    },
    {
        name: 'Jaguar XKR-S',
        horsepower: 550,
        dollar_value: 132000,
        in_stock: false
    },
    {
        name: 'Audi R8',
        horsepower: 525,
        dollar_value: 114200,
        in_stock: false
    },
    {
        name: 'Aston One-77',
        horsepower: 750,
        dollar_value: 1850000,
        in_stock: true
    }
]

// 1、使用函数组合fp.flowRight重新实现下面函数
let isLastInStock = function (cars) {
    let last_card = fp.last(cars)
    return fp.prop('in_stock', last_card)
}

function prop (key) {
    return function (last_card) {
        return fp.prop(key, last_card)
    }
}

const fn = fp.flowRight([prop('in_stock'), fp.last])
console.log('第1题-------------------')
console.log(fn(cars))

// --------------------------------------------------------------
// 2、使用fp.flowRight fp.prop fp.first 获取第一个card的name
const getCarFirstName = fp.flowRight([prop('name'), fp.first])
console.log('第2题-------------------')
console.log(getCarFirstName(cars))

// --------------------------------------------------------------------
// 3、使用帮助函数_average重构averageDollarValue,使用函数组合的方式实现
let _average = function(xs) {
    
    return fp.reduce(fp.add, 0, xs) / xs.length
}

/* let averageDollarValue = function(cars) {
    let dollar_values = fp.map(function(car) {
        return car.dollar_value
    }, cars)
    return _average(dollar_values)
}
console.log(averageDollarValue(cars)) */

let averageDollarValue = function(cars) {
    return fp.map(function(car) {
        return car.dollar_value
    }, cars)
}

let compose = function (f, g) {
    return function (x) {
        return f(g(x))
    }
}

let cFn = compose(_average, averageDollarValue)
console.log('第3题-------------------')
console.log(cFn(cars));

//-----------------------------------------------------
//4、使用flowRight写一个sanitizeNames()函数，返回一个下划线链接的小写字符串，把数组中的name转化为这种形式
// sanitizeNames(['Hello World']) => ['hello_world']

//let _underscore = fp.replace(/\w+/g, '_') // 这个正则表达式有问题，会把所有的字母都替换掉
let _underscore = fp.replace(/\s+/g, '_')
function sanitizeNames() {
    return fp.flowRight(fp.map(_underscore), fp.map(fp.lowerCase))
}
console.log('第4题-------------------')
console.log(sanitizeNames()(['Hello World']))
